<template>
  <div>
    <div v-show="searchStatus" class="box-shadow pad10 mgb10">
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Number"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="区域">
              <Selector v-model="queryParams.Area" category="学校区域" />
            </el-form-item>
            <el-form-item label="场地">
              <Selector v-model="queryParams.Place" category="全部场地" />
            </el-form-item>
            <el-form-item label="分类">
              <Selector v-model="queryParams.Type" category="6S类型" />
            </el-form-item>
            <el-form-item label="描述">
              <el-input
                v-model="queryParams.Description"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="状态">
              <el-select
                v-model="queryParams.State"
                clearable
                placeholder="请选择"
              >
                <el-option label="待处理" :value="1"></el-option>
                <el-option label="待确认" :value="2"></el-option>
                <el-option label="已完成" :value="3"></el-option>
              </el-select>
            </el-form-item>
          </div>
          <div class="flex acenter jend fnw">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>

    <MyTable
      :tableList="tableList"
      :total="Total"
      :columns="columns"
      v-model:page="page"
      v-model:searchStatus="searchStatus"
      :btnList="['delete']"
      @getList="getList"
      @delete="handleDelete"
      @link="handleCheck"
      @custom="handleCustom"
      :customBtn="[
        { name: '驳回', rule: { key: 'State', status: 2 }, color: '#909399' },
        { name: '确认', rule: { key: 'State', status: 2 }, color: '#67c23a' },
        { name: '处理', rule: { key: 'State', status: 1 }, color: '#409eff' }
      ]"
    >
      <template v-slot:tabTop>
        <div style="width: 500px" class="flex acenter">
          <el-button
            style="display: inline-block"
            type="primary"
            v-hasPermi="['MySix:add']"
            icon="CirclePlusFilled"
            @click="handleAdd"
            >添加问题</el-button
          >
          <el-tabs
            v-model="queryParams.IsMy"
            @tab-change="tabChange"
            style="margin: 0 0 0 20px"
            class="nmg"
          >
            <el-tab-pane :name="1" label="我发起的"> </el-tab-pane>
            <el-tab-pane :name="2" label="需我处理"></el-tab-pane>
          </el-tabs>
        </div>
      </template>
    </MyTable>
    <MyDialog
      v-model:show="show"
      :formRef="formRef"
      :title="title"
      @confirm="confirm"
    >
      <el-form
        :model="formData"
        ref="formRef"
        label-width="110px"
        :inline="true"
        class="wid100"
        :rules="rules"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="区域" prop="Area">
              <Selector
                @getItem="areaChange"
                v-model="formData.Area"
                category="学校区域"
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="场地" prop="ID_Place">
              <div v-if="formData.Area" style="width: 100%">
                <Selector
                  @getItem="placeChange"
                  v-model="formData.ID_Place"
                  :query="{
                    ID_Area: formData.Area
                  }"
                  category="全部场地"
                />
              </div>
              <div v-else>请先选择区域</div>
            </el-form-item>
          </el-col>
          <el-col :span="8"
            ><el-form-item label="问题分类" prop="ID_Type">
              <Selector
                v-model="formData.ID_Type"
                category="6S类型"
              /> </el-form-item
          ></el-col>
        </el-row>
        <el-row>
          <el-form-item label="6s执行项">
            <el-table
              :data="sixItemList"
              style="width: 100%"
              row-class-name="TableRowClass"
              header-row-class-name="TableHeaderClass"
            >
              <el-table-column
                type="index"
                label="序号"
                width="50"
                :align="'center'"
              />
              <el-table-column
                prop="Code"
                label="编号"
                width="180"
                :align="'center'"
              />
              <el-table-column prop="Content" label="内容" :align="'center'" />
              <el-table-column
                prop="State"
                label="状态"
                width="80"
                :align="'center'"
              >
                <template v-slot="{ row }">
                  <el-icon
                    v-if="row.State == 1"
                    @click="row.State = 2"
                    color="#67C23A"
                    :size="26"
                    class="pointer"
                    ><CircleCheckFilled
                  /></el-icon>
                  <el-icon
                    v-if="row.State == 2"
                    @click="row.State = 1"
                    color="#F56C6C"
                    :size="26"
                    class="pointer"
                    ><CircleCloseFilled
                  /></el-icon>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-row>
        <el-row style="flex-wrap: nowrap">
          <el-form-item label="问题描述" prop="Description">
            <el-input
              v-model="formData.Description"
              placeholder="请输入"
              clearable
              type="textarea"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item
            label="预计完成时间"
            prop="ExpectTime"
            label-width="110px"
          >
            <el-date-picker
              v-model="formData.ExpectTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              :disabled-date="disabledDate"
              placeholder="请选择"
              style="width: 220px !important"
            />
          </el-form-item>
        </el-row>
        <el-row>
          <el-form-item label="附件">
            <FileUpload
              :detail="false"
              v-model:fileList="fileList"
            ></FileUpload>
          </el-form-item>
        </el-row>
      </el-form>
    </MyDialog>
    <MyDialog v-model:show="detailShow" :title="title" :showFooter="false">
      <SixDetail v-model="detailData" />
    </MyDialog>
    <MyDialog
      :width="700"
      v-model:show="editShow"
      :title="title"
      :formRef="formRef"
      @confirm="editSixProblem"
    >
      <el-form
        :model="formData"
        ref="formRef"
        label-width="80px"
        :inline="true"
        class="wid100"
        :rules="rules"
      >
        <el-form-item
          label="处理方式"
          prop="Mode"
          v-if="title.includes('处理')"
        >
          <el-input
            v-model="formData.Mode"
            placeholder="请输入"
            clearable
            type="textarea"
          />
        </el-form-item>
        <el-form-item
          label="驳回原因"
          prop="BackReason"
          v-if="title.includes('驳回')"
        >
          <el-input
            v-model="formData.BackReason"
            placeholder="请输入"
            clearable
            type="textarea"
          />
        </el-form-item>
        <el-form-item label="附件">
          <FileUpload :detail="false" v-model:fileList="fileList"></FileUpload>
        </el-form-item>
      </el-form>
    </MyDialog>
  </div>
</template>

<script setup name="MySix">
import { ref, getCurrentInstance, onMounted } from 'vue';
import {
  GetSixSaleDataList_Page,
  GetSixSaleDataDetail,
  DelSixSaleData
} from '@/api/sixManage/SixData.js';
import SixDetail from '@/views/sixManage/SixData/sixDetail';
import { GetPlaceDetail } from '@/api/site/index.js';
import { GetSixSalePlanDetail } from '@/api/sixManage/executionPlan.js';
import {
  AddSixSaleData,
  ProcessSixSaleData,
  ConfirmSixSaleData,
  RebackSixSaleData
} from '@/api/sixManage/mySix.js';

const { proxy } = getCurrentInstance();
const tableList = ref([]);
const Total = ref(0);
const columns = ref([
  { label: '序号' },
  { label: '编号', prop: 'Number', link: true, self: true },
  { label: '区域名称', prop: 'AreaName' },
  { label: '场地名称', prop: 'PlaceName' },
  { label: '6s问题类型', prop: 'TypeName' },
  { label: '问题描述', prop: 'Description' },
  { label: '状态', prop: 'StateName', tag: true },
  { label: '创建时间', prop: 'CreateTime' },
  { label: '创建人', prop: 'CreateUser', user: true },

  { label: '最后一次处理方式', prop: 'Last_ProcessMode' },
  { label: '最后一次驳回原因', prop: 'Last_BackReason' },

  { label: '操作', width: 160 }
]);
proxy.$formatKey(columns.value);
const page = ref({
  PageIndex: 1,
  PageSize: 10
});

const searchStatus = ref(true);
const queryParams = ref({
  Code: '',
  Name: '',
  NoPage: '', //如果传"true"，则返回全部数据不分页
  IsMy: 1
});
const queryRef = ref();
const show = ref(false);
const title = ref();
const formRef = ref();
const rules = ref({
  Area: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Place: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Place: [{ required: true, message: '请选择', trigger: 'change' }],
  ID_Type: [{ required: true, message: '请选择', trigger: 'change' }],
  ExpectTime: [{ required: true, message: '请选择', trigger: 'change' }],
  Mode: [{ required: true, message: '请输入', trigger: 'blur' }],
  BackReason: [{ required: true, message: '请输入', trigger: 'blur' }]
});
const detailShow = ref(false);
const editShow = ref(false);
const formData = ref({});
const fileList = ref([]);
const detailData = ref({});
const status = ref({
  1: '待处理',
  2: '待确认',
  3: '已完成'
});
const types = ref({
  1: 'danger',
  2: 'warning',
  3: 'success'
});
const sixItemList = ref([]);
onMounted(() => {
  getList();
});

function handleCustom(val) {
  switch (val.btnName) {
    case '处理':
      sixEdit(val);
      break;
    case '驳回':
      sixBack(val);
      break;
    case '确认':
      sixconfirm(val);
      break;
  }
}

function tabChange(val) {
  getList();
}

async function handleCheck(row) {
  try {
    let res = await GetSixSaleDataDetail({ ID: row.ID });

    detailData.value = res.data;
    detailShow.value = true;
    title.value = '问题详情';
  } catch (error) {
    console.log(error);
  }
}

async function placeChange() {
  try {
    if (!formData.value.ID_Place) {
      sixItemList.value = [];
      return;
    }
    let res = await GetPlaceDetail({ ID: formData.value.ID_Place });
    let ID_6SPlan = res.data.Info?.ID_6SPlan;
    if (!ID_6SPlan) return proxy.$modal.msgError('该场地没有绑定6S方案');
    let planDetail = await GetSixSalePlanDetail({ ID: ID_6SPlan });
    planDetail.data.Items?.forEach(item => {
      item.State = 1;
    });
    sixItemList.value = planDetail.data.Items;
  } catch (error) {
    console.log(error);
  }
}

function areaChange() {
  formData.value.ID_Place = '';
  sixItemList.value = [];
}

async function getList() {
  try {
    show.value = false;
    detailShow.value = false;
    editShow.value = false;
    let query = {
      ...queryParams.value,
      ...page.value
    };
    let res = await GetSixSaleDataList_Page(query);
    res.data.List?.forEach(item => {
      item.StateName = filterState(item);
    });
    tableList.value = res.data.List;
    Total.value = res.data.Total;
  } catch (error) {
    console.log(error);
  }
}

async function editSixProblem(val) {
  try {
    if (val) {
      let query = {
        ...formData.value,
        Files: fileList.value?.map(item => {
          return { FileID: item.ID, Sort: item.Sort };
        })
      };
      if (title.value.includes('处理')) {
        await ProcessSixSaleData(query);
        proxy.$modal.msgSuccess('处理成功');
      } else {
        await RebackSixSaleData(query);
        proxy.$modal.msgSuccess('驳回成功');
      }
      getList();
    }
  } catch (error) {
    console.log(error);
  }
}
function sixBack(row) {
  formData.value = {};
  formData.value.ID_SixSaleData = row.ID;
  title.value = '驳回问题';
  fileList.value = [];
  editShow.value = true;
}
async function sixconfirm(row) {
  try {
    await ConfirmSixSaleData({ ID: row.ID });
    proxy.$modal.msgSuccess('确认成功');
    getList();
  } catch (error) {
    console.log(error);
  }
}
async function sixEdit(row) {
  formData.value = {};
  formData.value.ID_SixSaleData = row.ID;
  title.value = '处理问题';
  fileList.value = [];
  editShow.value = true;
  console.log(row);
}

async function confirm(val) {
  try {
    if (val) {
      let query = {
        ...formData.value,
        Files: fileList.value?.map(item => {
          return { FileID: item.ID, Sort: item.Sort };
        }),
        Items: sixItemList.value?.map(item => {
          return {
            Code: item.Code,
            Content: item.Content,
            State: item.State
          };
        })
      };
      await AddSixSaleData(query);
      proxy.$modal.msgSuccess('添加成功');
      getList();
    }
  } catch (error) {
    console.log(error);
  }
}

function filterState(item) {
  return [
    {
      type: types.value[item.State],
      color: '',
      effect: 'dark',
      size: '',
      name: status.value[item.State]
    }
  ];
}
function handleEdit(row) {
  title.value = '修改';
  show.value = true;
}
async function handleDelete(row) {
  try {
    await DelSixSaleData({ ID: row.ID });
    proxy.$modal.msgSuccess('删除成功');
    getList();
  } catch (error) {
    console.log(error);
  }
}
function handleAdd() {
  title.value = '添加6S问题';
  fileList.value = [];
  formData.value = {};
  sixItemList.value = [];
  show.value = true;
}
function disabledDate(date) {
  return date.getTime() < new Date().getTime() - 24 * 60 * 60 * 1000;
}
function handleQuery() {
  page.value.PageIndex = 1;
  getList();
}
function resetQuery() {
  queryParams.value = {
    Code: '',
    Name: '',
    NoPage: '',
    IsMy: 1
  };
  handleQuery();
}
</script>

<style lang="scss" scoped></style>
